'''
版权: Copyright (c) 2019 red

文件: client.py
创建日期: Monday January 7th 2019
作者: pao
说明:
1、分布式计算客户端
'''
import jsonrpcclient
import datetime

FUNC_NAME_GET_TASK = 'distribute.get_task'
FUNC_NAME_RETURN_TASK_ERROR = 'distribute.return_task_error'
FUNC_NAME_RETURN_TASK_VALUE = 'distribute.return_task_value'


class DistributeCalculatingClient:
    # 分布式计算客户端
    def __init__(self, server_url):
        # 构造函数
        self.history = []
        self.server_url = server_url

    def __get_task_and_calculate(self):
        # 获取任务并计算
        start_time = datetime.datetime.now()
        task_request = jsonrpcclient.request(
            self.server_url, FUNC_NAME_GET_TASK)
        task = task_request.data.result

        # 计算
        try:
            stat_calc_time = datetime.datetime.now()
            task_result = 'task函数将结果写到此变量中'
            exec(task.func, None, {
                'task_index': task.task_index,
                'args': task.args
            })
            result = task_result
            end_calc_time = datetime.datetime.now()
        except Exception as err:
            jsonrpcclient.request(
                self.server_url, FUNC_NAME_RETURN_TASK_ERROR, task.job_index, task.task_index, err)
            end_time = datetime.datetime.now()

            self.history.append({
                'job_index': task.job_index,
                'task_index': task.task_index,
                'func': task.func,
                'error': err,
                'status': 'failed',
                'start_time': start_time,
                'end_time': end_time,
                'stat_calc_time': stat_calc_time,
                'end_calc_time': end_calc_time
            })
        else:
            jsonrpcclient.request(
                self.server_url, FUNC_NAME_RETURN_TASK_VALUE, task.job_index, task.task_index, result)
            end_time = datetime.datetime.now()
            self.history.append({
                'job_index': task.job_index,
                'task_index': task.task_index,
                'func': task.func,
                'result': result,
                'status': 'success',
                'start_time': start_time,
                'end_time': end_time,
                'stat_calc_time': stat_calc_time,
                'end_calc_time': end_calc_time
            })
